package com.miyake.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.Widget;

public class SelectionBarComposite extends Composite {
	interface SelectionBarHandler {
		void onSelect(String name);
	};
	private List<SelectionBarHandler> handlers = new ArrayList<SelectionBarHandler>();
	public void addSelectionBarHandler(SelectionBarHandler handler) {
		handlers.add(handler);
	}
	public void fireOnSelect(String name) {
		for (SelectionBarHandler handler : handlers) {
			handler.onSelect(name);
		}
	}
	private HorizontalPanel horizontalPanel;
	
	public SelectionBarComposite() {
		
		VerticalPanel verticalPanel = new VerticalPanel();
		initWidget(verticalPanel);
		verticalPanel.setWidth("100%");
		
		horizontalPanel = new HorizontalPanel();
		horizontalPanel.setWidth("100%");
		horizontalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		verticalPanel.add(horizontalPanel);
	}

	public void addButton(final String name) {
		//tglbtnUpText.setStylePrimaryName("buttonCaption");
		final ToggleButton tglbtnUpText = new ToggleButton();
		tglbtnUpText.setWidth("130px");
		//tglbtnUpText.setHTML("<DIV ALIGN=\"center\">" + name + "</DIV>");
		tglbtnUpText.setText(name);
		tglbtnUpText.setStylePrimaryName("toolBarButton");
		
		horizontalPanel.add(tglbtnUpText);
		tglbtnUpText.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				tglbtnUpText.setStylePrimaryName("toolBarButtonDown");
				cancelSelection((ToggleButton)event.getSource());
				fireOnSelect(name);
			}
		});
	}

	protected void cancelSelection(ToggleButton source) {
		for (int i = 0; i < horizontalPanel.getWidgetCount(); i++) {
			Widget widget = horizontalPanel.getWidget(i);
			if (widget instanceof ToggleButton && source != widget) {
				ToggleButton button = ((ToggleButton)horizontalPanel.getWidget(i));
				button.setDown(false);
				button.setStylePrimaryName("toolBarButton");
			}
		}
	}
}
